import 'dart:io';
import 'dart:async';

import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image_crop/image_crop.dart';
import 'package:image_picker/image_picker.dart';

class CropImageRoute extends StatefulWidget {
  ImageSource _source;

  CropImageRoute(this._source);

  @override
  _CropImageRouteState createState() => new _CropImageRouteState();
}

class _CropImageRouteState extends State<CropImageRoute> {
  final cropKey = GlobalKey<CropState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _openImage();
  }

  File _file;

  Future<void> _openImage() async {
    final pickedFile = await ImagePicker().getImage(source: widget._source);
    if (pickedFile == null) {
      Get.back();
      return;
    }

    final file = File(pickedFile.path);
    // final sample = await ImageCrop.sampleImage(
    //   file: file,
    //   preferredSize: context.size.longestSide.ceil(),
    // );
    _file?.delete();

    setState(() {
      _file = file;
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Container(
          color: Colors.black,
          padding: const EdgeInsets.symmetric(vertical: 40.0, horizontal: 20.0),
          child: _file == null ? SizedBox() : _buildCroppingImage(),
        ),
      ),
    );
  }

  Widget _buildCroppingImage() {
    return Column(
      children: <Widget>[
        Expanded(
          child: Crop.file(
            _file,
            key: cropKey,
            aspectRatio: 1 / 1,
          ),
        ),
        Container(
          padding: const EdgeInsets.only(top: 20.0),
          alignment: AlignmentDirectional.center,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              OutlinedButton(
                  onPressed: () => Get.back(),
                  child: Text(
                    "取消",
                    style: TextStyle(
                      fontSize: sp(15),
                      color: AppColor.colorTheme,
                    ),
                  ),
                  style: OutlinedButton.styleFrom(
                      side: BorderSide(color: AppColor.colorTheme),
                    minimumSize:Size(width(100), height(44))
                  )),
              TextButton(
                  onPressed: () => _cropImage(),
                  child: Text(
                    "确认",
                    style: TextStyle(
                      fontSize: sp(15),
                      color: Colors.white,
                    ),
                  ),
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(AppColor.colorTheme),
                    padding: MaterialStateProperty.all(EdgeInsets.all(10)),
                    minimumSize:
                        MaterialStateProperty.all(Size(width(100), height(44))),
                  )),

              // _buildOpenImage(),
            ],
          ),
        )
      ],
    );
  }

  Future<void> _cropImage() async {
    final scale = cropKey.currentState.scale;
    final area = cropKey.currentState.area;
    if (area == null) {
      // cannot crop, widget is not setup
      return;
    }

    // scale up to use maximum possible number of pixels
    // this will sample image in higher resolution to make cropped image larger
    final sample = await ImageCrop.sampleImage(
      file: _file,
      preferredSize: (2000 / scale).round(),
    );

    final file = await ImageCrop.cropImage(
      file: sample,
      area: area,
    );

    sample.delete();

    debugPrint('裁剪后：$file');
    Get.back(result: file.path);
  }
}
